﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

using Galaktika.BI.Runtime.Services;
using Galaktika.BI.Silverlight.Commands;
using Galaktika.BI.Silverlight.Services;

using Ranet.Olap.Core.Providers.ClientServer;

namespace Galaktika.BI.Silverlight.Controls
{
    public static class AnalysisTransactionManager
    {
        public static event EventHandler BeforeCommitTransaction;
        public static event EventHandler BeforeRollbackTransaction;
        public static event EventHandler<TransactionCommandResultEventArgs> AfterCommandComplete;
        private static Dictionary<string, bool> m_HasPendingChanges = new Dictionary<string,bool>();

        public static void SetHasPendingChanges(string connectionName)
        {
            SetHasPendingChanges(connectionName, true);
        }

        public static bool GetHasPendingChanges(string connectionName)
        {
            lock (m_HasPendingChanges)
            {
                if (m_HasPendingChanges.ContainsKey(connectionName))
                {
                    return m_HasPendingChanges[connectionName];
                }

                return false;
            }
        }


        private static void SetHasPendingChanges(string connectionName, bool has)
        {
            lock (m_HasPendingChanges)
            {
                m_HasPendingChanges[connectionName] = has;
                OnAfterCommandComplete(connectionName);//, has);
            }
        }

        private static void OnAfterCommandComplete(string connectionName)//, bool success)
        {
            var handler = AfterCommandComplete;
            if (handler != null)
            {
                handler(null, new TransactionCommandResultEventArgs(connectionName));//, success));
            }
        }

        private static void OnBeforeCommitTransaction()
        {
            EventHandler handler = BeforeCommitTransaction;
            if (handler != null)
            {
                handler(null, EventArgs.Empty);
            }
        }

        private static void OnBeforeRollbackTransaction()
        {
            EventHandler handler = BeforeRollbackTransaction;
            if (handler != null)
            {
                handler(null, EventArgs.Empty);
            }
        }

        public static bool Commit(IBindingContext context, string connectionName)
        {
            OnBeforeCommitTransaction();
            string id = ((IUniquedObject)context).Id;
            return ExecuteCommand(
                CommandBuilder.CreateCommitTransactionSchema(id, connectionName), 
                context,
                connectionName);
        }

        public static bool Rollback(IBindingContext context, string connectionName)
        {
            OnBeforeRollbackTransaction();
            string id = ((IUniquedObject)context).Id;
            return ExecuteCommand(
                CommandBuilder.CreateRollbackTransactionSchema(id, connectionName), 
                context,
                connectionName);
        }

        private static bool ExecuteCommand(InvokeSchema schema, IBindingContext context, string connectionName)
        {
            IServiceProvider services = context.Services;
            using (var cmd = CommandDispatcher.Dispatch(schema))
            {
                InvokeResultSchema res = cmd.Invoke();
                if (res.ContentType == KnownContentTypes.Error)
                {
                    IOutputService output = (IOutputService)services.GetService(typeof(IOutputService));
                    if (output != null)
                    {
                        output.WriteException(res.Content);
                    }

                    //SetHasPendingChanges(connectionName, false);
                    return false;
                }

                context.IsDirty = true;
                ClientCache.Instance.Clear();
                SetHasPendingChanges(connectionName, false);
                return true;
            }
        }
    }

    public class TransactionCommandResultEventArgs : EventArgs
    {
        public TransactionCommandResultEventArgs(string connectionName)//, bool success)
        {
            //this.Succeess = success;
            this.ConnectionName = connectionName;
        }

        public readonly string ConnectionName;
        //public readonly bool Succeess;
    }
}
